package cn.m1c.cntt.wuhan2020.cnttlifegoods.weixin.controller

import cn.m1c.cntt.wuhan2020.cnttlifegoods.common.enums.StatusCode
import cn.m1c.cntt.wuhan2020.cnttlifegoods.common.model.ResultVo
import cn.m1c.cntt.wuhan2020.cnttlifegoods.common.utils.get
import cn.m1c.cntt.wuhan2020.cnttlifegoods.common.utils.getUUID
import cn.m1c.cntt.wuhan2020.cnttlifegoods.weixin.service.WeixinService
import cn.m1c.cntt.wuhan2020.cnttlifegoods.weixin.utils.SHA1WeChatShareUtil
import com.alibaba.fastjson.JSON
import org.apache.logging.log4j.kotlin.Logging
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import java.util.*
import javax.annotation.Resource
import kotlin.collections.HashMap

/**
 * 此文件由于涉及具体的小程序参数，故未经脱敏不得提交代码
 */
@Controller
@RequestMapping("/weixin")
class WeixinController  : Logging {
    var appId = ""
    var secret = ""

    @Resource
    lateinit var weixinService: WeixinService

//    @GetMapping("/initWeixinParam")
//    @ResponseBody
//    fun initWeixinParam(url:String):String{
//        var ononcestr = UUID.randomUUID().getUUID()
//        var jsapi_ticket = weixinService.ticket()
//        var timestamp = (System.currentTimeMillis()/1000) .toString()
//        var signMap = hashMapOf("noncestr" to ononcestr,"jsapi_ticket" to jsapi_ticket,"timestamp" to timestamp,"url" to url)
//        var signature = SHA1WeChatShareUtil.SHA1(signMap)
//        signMap.remove("jsapi_ticket")
//        signMap.put("signature",signature)
//        signMap.put("appId",appId)
//        return JSON.toJSONString(ResultVo<HashMap<String,String>>(data = signMap))
//    }
    @GetMapping("/codeToParam")
    @ResponseBody
    fun codeToParam(code:String):String{
        logger.info("cod is $code")
        var jsCode = code
        var response = get("https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$secret&js_code=$jsCode&grant_type=authorization_code")
        logger.info("response is $response")
        var openId = JSON.parseObject(response).getString("openid")
        var resultVo = ResultVo<String>(data = openId)
        if(openId == null || openId.length<1){
            resultVo = ResultVo<String>(code = StatusCode.failed.code,message = "code过期，重新获取code",data = openId)
        }
        return JSON.toJSONString(resultVo)
    }
}